package com.papper.mng.utils;

import com.papper.common.config.LocalConfig;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * COOKIE操作类
 *
 * @author chand.chen
 */
public abstract class CookieUtil {
    private static String COOKIE_DOMAIN = "ideallife.com";

    static {
        try {
            String domin = LocalConfig.I().GS(LocalConfig.COOKIE_DOMAIN);
            if (domin != null && !domin.isEmpty()) {
                COOKIE_DOMAIN = domin;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据cookie名称取值
     *
     * @param key
     * @param _request
     * @return
     * @throws UnsupportedEncodingException
     */
    public final static String getCookie(String key, HttpServletRequest _request) {
        Cookie[] cookies = _request.getCookies();
        if (cookies == null) {
            return null;
        }

        String value = null;
        for (Cookie cookie : cookies) {
            String cname = cookie.getName();
            if (cname.equals(key)) {
                try {
                    value = URLDecoder.decode(cookie.getValue(), "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }
        return value;
    }

    /**
     * 设置页面cookie
     *
     * @param _response
     * @param key
     * @param value
     * @param cookieAge
     * @throws UnsupportedEncodingException
     */
    public final static void setLocalInfo(HttpServletResponse _response, String key, String value, int cookieAge) {
        Cookie cookieToken;
        try {
            cookieToken = new Cookie(key, URLEncoder.encode(value, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return;
        }
        cookieToken.setDomain(COOKIE_DOMAIN);
        cookieToken.setPath("/");
        cookieToken.setMaxAge(cookieAge);

        _response.addCookie(cookieToken);
    }

    /**
     * 去除页面cookie
     *
     * @param _response
     * @param key
     */
    public final static void removeLocalInfo(HttpServletResponse _response, String key) {
        Cookie cookieToken = new Cookie(key, "");
        cookieToken.setPath("/");
        cookieToken.setMaxAge(0);
        cookieToken.setSecure(true);
        _response.addCookie(cookieToken);
    }
}
